# -*- coding: utf-8 -*-            
# @Author : chenliang
# @Time : 2024/10/26 13:58
import requests
import json
from datetime import datetime


class Ding(object):

    def ding_hami(self,content_text):
        # 钉钉机器人的Webhook URL
        url = "https://oapi.dingtalk.com/robot/send?access_token=a7559e1723520fd260c674e404e34b03cb328c73190e8e2e3ea44275d6c2fd77"
        # 消息内容
        message = {
            "msgtype": "text",
            "text": {
                "content": content_text
            }

        }
        # 发送请求
        response = requests.post(url, data=json.dumps(message), headers={'Content-Type': 'application/json'})

        # 打印响应
        print(response.text)

    def ding_hami_xiaoshou(self, content_text):
        # 钉钉机器人的Webhook URL
        url = "https://oapi.dingtalk.com/robot/send?access_token=a6f3e45a34ff2ccf6dc0fb2f441331b46a1edadd6e809a84686f417b9d80cbe4"
        # 消息内容
        message = {
            "msgtype": "text",
            "text": {
                "content": content_text
            }

        }
        # 发送请求
        response = requests.post(url, data=json.dumps(message), headers={'Content-Type': 'application/json'})

        # 打印响应
        print(response.text)

    # 待处理bug
    def generate_dingtalk_message(self,assignee='开发', bugs=[], phone=''):
        #current_time = "2025-02-17 16:36"  # 根据实际获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        if assignee=='开发':
            bug_details = ''.join([
                f"➠ **#{bug['id']}** {bug['title']}\n"
                f"　 优先级：'{bug['priority']} | 创建时间 : '{bug['create_time']}'\n\n"
                ##f"　 创建时间：{bug['create_time']}｜[查看详情]({bug['url']})\n\n"
                for bug in bugs
            ])
        else:
            bug_details = ''.join([
                f"➠ **#{bug['id']}** {bug['title']}\n"
                f"　 状态：'{bug['status']}'｜优先级：'{bug['priority']} | 创建时间 : '{bug['create_time']}'\n\n"
                ##f"　 创建时间：{bug['create_time']}｜[查看详情]({bug['url']})\n\n"
                for bug in bugs
            ])

        message = {
            "msgtype": "markdown",
            "markdown": {
                "title": "待处理缺陷提醒",
                "text": (
                    f"#### 🚨 {assignee}的待处理缺陷（共{len(bugs)}条,包含P3）\n"
                    f"**当前时间**：{current_time}\n\n"
                    f"{bug_details}\n"
                    #f"@{phone}"
                )
            },
            "at":{
                "atMobiles": f'[{phone}]',
                "isAtAll": True
            }
        }
        return message

        # 待处理bug

    def generate_dingtalk_message_dict(self, assignee='开发', bugs_dict={}, phone=''):
        # current_time = "2025-02-17 16:36"  # 根据实际获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M")

        total_bugs = sum(len(bugs) for bugs in bugs_dict.values())  # 新增总数统计
        # 按人分组生成缺陷内容
        bug_details = []
        for assignee_name, bugs in bugs_dict.items():
            # 每个负责人的分组标题
            group_title = f"➠ #### {assignee_name}的待处理（共{len(bugs)}条）\n\n"

            # 根据负责人类型生成缺陷详情
            bug_items = []
            for bug in bugs:
                if assignee == '开发':
                    bug_str = (
                        f"  **#{bug['id']}** {bug['title']}\n"
                        f"　 优先级：{bug['priority']} | 创建时间：{bug['create_time']}\n\n"
                    )
                else:
                    bug_str = (
                        f"  **#{bug['id']}** {bug['title']}\n"
                        f"　 状态：{bug['status']} | 优先级：{bug['priority']} | 创建时间：{bug['create_time']}\n\n"
                    )
                bug_items.append(bug_str)

            # 合并当前负责人的所有缺陷项
            group_content = group_title + ''.join(bug_items)
            bug_details.append(group_content)


        if assignee=='开发':
            message = {
                "msgtype": "markdown",
                "markdown": {
                    "title": "待处理缺陷提醒",
                    "text": (
                        f"#### 🚨 开发待处理缺陷提醒（总数：{total_bugs}条）\n"
                        f"**当前时间**：{current_time}\n\n"
                        f"{''.join(bug_details)}\n"
                    )
                },
                "at": {
                    "atMobiles": f"[{phone}]" if phone else "[]",
                    "isAtAll": True if not phone else False
                }
            }
            return message

        if assignee=='测试':
            message = {
                "msgtype": "markdown",
                "markdown": {
                    "title": "测试待验证",
                    "text": (
                        f"####  测试待验证（总数：{total_bugs}条）\n"
                        f"**当前时间**：{current_time}\n\n"
                        f"{''.join(bug_details)}\n"
                    )
                },
                "at": {
                    "atMobiles": f"[{phone}]" if phone else "[]",
                    "isAtAll": True if not phone else False
                }
            }
            return message

    # 当天关闭的bug
    def closed_dingtalk_message(self,assignee='', bugs=[], phone=''):
        #current_time = "2025-02-17 16:36"  # 根据实际获取当前时间
        #current_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        bug_details = ''.join([
            f"➠ **#{bug['id']}** {bug['title']}\n"
            f"　 状态：'{bug['status']}'｜优先级：'{bug['priority']} | 创建时间 : '{bug['create_time']}'\n\n"
            ##f"　 创建时间：{bug['create_time']}｜[查看详情]({bug['url']})\n\n"
            for bug in bugs
        ])


        message = {
            "msgtype": "markdown",
            "markdown": {
                "title": "当天解决bug提醒",
                "text": (
                    f"#### ✅ 今日关闭缺陷（共{len(bugs)}条）\n"
                    #f"{bug_details}\n"
                    #f"@{phone}"
                )
            },
            "at":{
                "atMobiles": f'[{phone}]',
                "isAtAll": False
            }
        }
        return message

        # 当天关闭的bug

    def ak_message(self, assignee='', ak={}, phone=''):
        # current_time = "2025-02-17 16:36"  # 根据实际获取当前时间
        # current_time = datetime.now().strftime("%Y-%m-%d %H:%M")

        message = {
            "msgtype": "markdown",
            "markdown": {
                "title": "生产ak告警",
                "text": (
                    f"#### ❌ 失效ak：\n"
                    f"{ak}\n"
                    f"@{phone}"
                )
            },
            "at": {
                "atMobiles": f'[{phone}]',
                "isAtAll": False
            }
        }
        return message


    def send_to_dingtalk(self,webhook_url, message):
        headers = {'Content-Type': 'application/json'}
        try:
            response = requests.post(webhook_url, json=message, headers=headers)
            return response.status_code == 200
        except Exception as e:
            print(f"消息发送失败：{str(e)}")
            return False


if __name__ == "__main__":
    content_text = """
    车辆
    换行
    """
    print(content_text)
    #Ding().ding_hami("测试")

